﻿namespace SyncDemo.Sync.Utils
{
    public abstract class MemoryBuffer : IDisposable
    {
      
        #region props
        public byte[] SendBuffer { get; }

        public byte[] ReceiveBuffer { get; }
        #endregion

        #region fields
        protected MemoryStream _sendMemoryStream;
        protected MemoryStream _receiveMemoryStream;
        
        #endregion

        #region ctors

        public MemoryBuffer() : this(128)
        {

        }

        public MemoryBuffer(int size)
        {
            SendBuffer = new byte[size];
            ReceiveBuffer = new byte[size];
            _sendMemoryStream = new MemoryStream(SendBuffer);
            _receiveMemoryStream = new MemoryStream(ReceiveBuffer);

            Loaded();
        }

        #endregion

        #region methods

        protected virtual void Loaded()
        {

        }

        ///<summary>将对象其序列化到缓冲区中。</summary>
        public virtual void Serialize<T>(T obj)
        {
           
        }

        ///<summary>将缓冲区内的数据解析指定对象。</summary>
        public virtual bool TryDeserialize<T>(out T result)
        {
            result = default;
            return false;
        }

     
        public void Dispose()
        {
            //_streamWriter?.Close();
            //_streamWriter?.Dispose();
            //_streamWriter = null;
            _sendMemoryStream?.Close();
            _sendMemoryStream?.Dispose();
            _sendMemoryStream = null;

            _receiveMemoryStream?.Close();
            _receiveMemoryStream?.Dispose();
            _receiveMemoryStream = null;

            
        }

        #endregion

    }
}
